import { Component, OnInit, OnDestroy } from '@angular/core'
import { FormBuilder, FormGroup, Validators } from '@angular/forms'
import { Subscription } from 'rxjs'
import { take } from 'rxjs/operators'
import { NzMessageService } from 'ng-zorro-antd'
import { StoreDataService } from '../../store-data.service'
import { makeAllControlDirty } from 'app/utils/helpers'
import { AcquirerService } from 'app/routes/acquirer/acquirer.service'
import { I18NService } from '@core'
import { NewPageAccessor } from '@shared/components/new-page/new-page.interface'
import { StoreCreate } from '@shared/interfaces/store'

@Component({
  selector: 'app-store-new-risk-control',
  templateUrl: './risk-control.component.html',
  styleUrls: ['./risk-control.component.less'],
})
export class StoreNewRiskControlComponent implements NewPageAccessor, OnInit, OnDestroy {
  constructor(
    private msg: NzMessageService,
    private fb: FormBuilder,
    private storeDataService: StoreDataService,
    private acquirerService: AcquirerService,
    private i18n: I18NService,
  ) {}

  data: any
  payload: StoreCreate
  form: FormGroup
  errorTips = {}
  isSupportRisk = false // 是否支持风控
  isSupportPostRisk = false // 是否支持事后风控
  insCode = ''
  postRCFormSelectSub: Subscription

  ngOnInit() {
    this.storeDataService.value$.pipe(take(1)).subscribe(store => {
      this.payload = store
      const { insCode } = this.payload.store.common
      this.insCode = insCode
      this.acquirerService
        .getOne(insCode)
        .pipe(take(1))
        .subscribe(acqFull => {
          const { isSupportRisk, isSupportPostRisk } = acqFull.institution.common.feature
          this.isSupportRisk = isSupportRisk
          this.isSupportPostRisk = isSupportPostRisk
        })

      this.form = this.fb.group({
        rc: this.fb.group({
          schemeCode: [{ value: '', disabled: true }],
        }),
        postRC: this.fb.group({
          selectedScheme: [''],
          schemeCode: [{ value: '', disabled: true }],
          schemeName: [{ value: '', disabled: true }],
          schemeDesc: [{ value: '', disabled: true }],
        }),
      })
      const postRCForm = this.form.get('postRC')
      if (this.payload.postRiskSchemeCode) {
        postRCForm.get('selectedScheme').setValue(this.payload.selectedPostRiskScheme)
        postRCForm
          .get('schemeCode')
          .setValue(this.payload.selectedPostRiskScheme ? this.payload.selectedPostRiskScheme.schemeCode : '')
        postRCForm
          .get('schemeName')
          .setValue(this.payload.selectedPostRiskScheme ? this.payload.selectedPostRiskScheme.schemeName : '')
        postRCForm
          .get('schemeDesc')
          .setValue(this.payload.selectedPostRiskScheme ? this.payload.selectedPostRiskScheme.schemeDesc : '')
      }
      this.postRCFormSelectSub = postRCForm.get('selectedScheme').valueChanges.subscribe(value => {
        postRCForm.get('schemeCode').setValue(value ? value.schemeCode : '')
        postRCForm.get('schemeName').setValue(value ? value.schemeName : '')
        postRCForm.get('schemeDesc').setValue(value ? value.schemeDesc : '')
      })

      this.initErrorTips()
    })
  }

  ngOnDestroy(): void {
    this.postRCFormSelectSub.unsubscribe()
  }

  pushDataToStore(): void {
    const value = this.form.getRawValue()
    this.payload.riskSchemeCode = value.rc.schemeCode
    this.payload.selectedPostRiskScheme = value.postRC.selectedScheme
    this.payload.postRiskSchemeCode = value.postRC.schemeCode
    this.storeDataService.updateValue(this.payload)
  }

  checkValid(): boolean {
    // 如果机构不支持风控，则直接返回 true
    if (!this.isSupportRisk && !this.isSupportPostRisk) {
      return true
    }

    if (this.form.valid) {
      this.pushDataToStore()
      return true
    }

    makeAllControlDirty(this.form)
    this.msg.error(this.trans('GENERAL.NOTIFICATION.VALIDATION_FAIL'))
    return false
  }

  trans(key: string, params?: Object): string {
    return this.i18n.fanyi(key, params)
  }

  private initErrorTips() {
    this.errorTips = {
      selectedScheme: {
        required: this.trans('VALIDATION.REQUIRED_SELECT', { name: this.trans('BIZ.STORE.OTHER.RC.RC_SCHEME') }),
      },
    }
  }
}
